package com.hioove.core.web.mvc.route;

import com.hioove.core.model.base.config.MethodSupport;
import com.hioove.core.web.model.ServletRequest;
import com.hioove.core.web.model.ServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Objects;
import java.util.stream.Stream;

/**
 * web 调度器
 */
@Slf4j
public class Dispatch {

    public void run(ServletRequest servletRequest, ServletResponse servletResponse, HashMap<String, MethodSupport> dispatch) {
        String uri = servletRequest.getUrl();
        // 保证这个请求是被容器管理的
        Stream.of(uri).filter(s -> dispatch.containsKey(uri)).peek(s -> {
            log.debug("Request interface exception!!! url: {} ", uri);
            MethodSupport methodSupport = dispatch.get(uri);
            Object param = methodSupport.getParamTypes().size() == 0 ? null : servletRequest.getParam();
            final Object[] result = {null};
            Stream.of(param).filter(Objects::isNull).peek(o -> {
                try {
                    result[0] = methodSupport.getMethod().invoke(methodSupport.getInstance());
                } catch (Exception e) {
                }
            }).count();
            Stream.of(param).filter(Objects::nonNull).map(o -> methodSupport.getParamTypes()).peek(classes -> {
                try {
                    result[0] = methodSupport.getMethod().invoke(methodSupport.getInstance(), param);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).count();
            servletResponse.setContent(result[0]);
        }).count();
    }

}
